#include <QTextStream>
#include "historystorage.h"

HistoryStorage::HistoryStorage(){}

void HistoryStorage::setMaxSize(int size) {
    if (size <= 0)
        return;
    this->maxSize = size;
    int diff = this->history.length() - size;
    if (diff <= 0)
        return;
    while (diff -- > 0)
        this->history.removeAt(0);
}

int HistoryStorage::getMaxSize() {
    return this->maxSize;
}

int HistoryStorage::getHistoryNumber() {
    return this->history.length();
}

QString HistoryStorage::getPureAnswer(QString answer) {
    QString right = "</think>";
    QTextStream stream(&answer);
    QString line;
    int rightIdx = -1;
    int idx = 0;
    QString res = "";
    while (!stream.atEnd()) {
        line = stream.readLine();
        if (rightIdx == -1) {
            if (line == right) {
                rightIdx = idx;
            }
        } else {
            res += line + "\n";
        }
        ++ idx;
    }
    if (rightIdx == -1)
        return answer;
    return res.trimmed();
}

void HistoryStorage::push(const QString& question, const QString& answer) {
    this->history.push_back(
        QString("User: %1\nAI: %2\n").arg(question).arg(this->getPureAnswer(answer))
    );
    while (this->history.length() > this->maxSize)
        this->history.removeAt(0);
}

void HistoryStorage::clear() {
    this->history.clear();
}

QString HistoryStorage::toString() {
    QString res = "";
    for (const QString& message : this->history)
        res += message + "\n";
    return res;
}
